package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.entity.SystemService
import com.zxy.supplier_system.server.entity.SystemServiceSetting
import com.zxy.supplier_system.server.repository.SystemServiceRepository
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import kotlin.jvm.optionals.getOrNull

@Service
class SystemServiceService(
    private val systemServiceRepository: SystemServiceRepository,
    private val employeeService: EmployeeService
) : AuditingEntityListener() {

    companion object {
        const val SYSTEM_SERVICE_FIELD_NAME = "systemService"
    }

    @Transactional(readOnly = true)
    fun getCurrentSystemService(): SystemService {
        val employee = employeeService.currentAuditor.getOrNull()
        return employee?.systemService ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED)
    }

    @Transactional(readOnly = true)
    override fun touchForCreate(target: Any) {
        val anyClass = target::class.java
        val field = anyClass.getField(SYSTEM_SERVICE_FIELD_NAME)
        field.set(target, this.getCurrentSystemService())
    }

    @Transactional(readOnly = true)
    fun getCurrentSystemSetting(): SystemServiceSetting {
        return this.getCurrentSystemService().setting
    }

}
